////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.EntityClasses;
using RPSDAL.FactoryClasses;
using RPSDAL.DaoClasses;
using RPSDAL.RelationClasses;
using RPSDAL.ValidatorClasses;
using RPSDAL.TypedViewClasses;
using RPSDAL.StoredProcedureCallerClasses;
using RPSDAL.HelperClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;

public partial class BusinessRule : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        if (Parameters.LoggedUser != -1) 
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            if (!eRole.HasEditBusinessRules) 
            {
                Parameters.LoggedUser = -1;
                Response.Redirect("Default.aspx");
                return;
            }
        }

        ContactGroupCollection cContactGroups = new ContactGroupCollection();
        cContactGroups.GetMulti(null);

        cmbGroupContacts.DataSource = cContactGroups;
        cmbGroupContacts.DataTextField = ContactGroupFields.Name.Name;
        cmbGroupContacts.DataValueField = ContactGroupFields.ContactGroupId.Name;
        cmbGroupContacts.DataBind();

        LoadTemplates();
    }

    private void LoadTemplates() 
    {
        TemplateCollection cTemplates = new TemplateCollection();
        cTemplates.GetMulti(null);

        cmbTemplates.DataSource = cTemplates;
        cmbTemplates.DataTextField = TemplateFields.Name.Name;
        cmbTemplates.DataValueField = TemplateFields.TemplateId.Name;
        cmbTemplates.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //cmbType.Attributes.Add("OnChange", "TypeChange(this)");
            if (Request.QueryString["id"] != null) 
            {
                LoadBusinessRule(Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString())));
            }
        }
    }

    

    #region methods

    private void LoadBusinessRule(int businessRuleId) 
    {
        BusinessRuleEntity eBusinessRule = new BusinessRuleEntity(businessRuleId);
        txtRuleName.Text = eBusinessRule.Name;
        cmbType.SelectedValue = eBusinessRule.RuleType.ToString();
        cmbGroupContacts.SelectedValue = eBusinessRule.ContactGroupId.ToString();
        ckActive.Checked = eBusinessRule.Active;
        txtDescription.Text = eBusinessRule.Description;

        switch (eBusinessRule.RuleType) 
        {
            case Parameters.CALL_TYPE:
                txtFrom.Text = eBusinessRule.From.ToString();
                txtTo.Text = eBusinessRule.To.ToString();
                txtCallReason.Text = eBusinessRule.CallReason;
                break;
            case Parameters.LETTER_TYPE:
                cmbTemplates.SelectedValue = eBusinessRule.TemplateId.ToString();
                txtFrom.Text = eBusinessRule.From.ToString();
                txtTo.Text = eBusinessRule.To.ToString();
                break;
            case Parameters.MAIL_TYPE:
                cmbTemplates.SelectedValue = eBusinessRule.TemplateId.ToString();
                txtDaysFromContact.Text = eBusinessRule.NoDaysFromInitialContact.ToString();
                txtEmailSubject.Text = eBusinessRule.EmailSubject;
                break;
        }

        ShowExtraFields();
    }

    /// <summary>
    /// insert or modify business rule
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Save(object sender, EventArgs e)
    {
        Global.UserLogSave(Parameters.LoggedUser, "Save Business Rule");
        BusinessRuleEntity eBusinessRule = new BusinessRuleEntity();

        if (Page.IsPostBack && !String.IsNullOrEmpty(Request.QueryString["id"]))
        {
            eBusinessRule = new BusinessRuleEntity(Convert.ToInt32(Global.DecryptString(Request.QueryString["id"].ToString())));
        }

        int index = 0;
        if (eBusinessRule.IsNew || eBusinessRule.Name.ToUpper() != txtRuleName.Text.ToUpper()) 
        {
            BusinessRuleCollection cBusinessRule = new BusinessRuleCollection();
            IPredicateExpression filter = new PredicateExpression();
            filter.Add(BusinessRuleFields.Name == txtRuleName.Text);
            index = cBusinessRule.GetDbCount(filter);  
        }

        eBusinessRule.Name = txtRuleName.Text;

        //cBusinessRule.GetMulti(null);
        //int index;
        //bool bExist = false;
        //for (index = 0; index < cBusinessRule.Count; index++)
        //{
        //    if (cBusinessRule[index].Name == txtRuleName.Text)
        //    {
        //        bExist = true;
        //        break;
        //    }
        //}
        if (index == 0)
        {
            lblSteluta.Visible = false;
            lblRuleNameExist.Visible = false;
        }
        else
        {
            lblSteluta.Visible = true;
            lblRuleNameExist.Visible = true;
            return;
        }


        eBusinessRule.RuleType = Convert.ToInt32(cmbType.SelectedValue);
        eBusinessRule.Active = ckActive.Checked;
        eBusinessRule.TemplateId = Convert.ToInt32(cmbTemplates.SelectedValue);
        if (txtDaysFromContact.Text != "")
        {
            eBusinessRule.NoDaysFromInitialContact = Convert.ToInt32(txtDaysFromContact.Text);
        }
        if (txtFrom.Text != "") 
        {
            int dateFrom;

            if (!String.IsNullOrEmpty(txtFrom.Text) && Int32.TryParse(txtFrom.Text, out dateFrom))
            {
                eBusinessRule.From = dateFrom;
            }
        }

        if (txtTo.Text != "") 
        {
            int toFrom;

            if (!String.IsNullOrEmpty(txtTo.Text) && Int32.TryParse(txtTo.Text, out toFrom))
            {
                eBusinessRule.To = toFrom;
            }
        }

        if (eBusinessRule.To < eBusinessRule.From)
        {
            lblDateFrom.Visible = true;
            lblDateTo.Visible = true;
            lblDateExpected.Visible = true;
            return;
        }
        else
        {
            lblDateFrom.Visible = false;
            lblDateTo.Visible = false;
            lblDateExpected.Visible = false;
        }

        eBusinessRule.ContactGroupId = Convert.ToInt32(cmbGroupContacts.SelectedValue);
        eBusinessRule.Description = txtDescription.Text;
        eBusinessRule.RuleType = Convert.ToInt32(cmbType.SelectedValue);

        switch (eBusinessRule.RuleType) 
        {
            case Parameters.CALL_TYPE:
                eBusinessRule.CallReason = txtCallReason.Text;
                break;
            case Parameters.MAIL_TYPE:
                eBusinessRule.EmailSubject = txtEmailSubject.Text;
                break;
        }

        eBusinessRule.Save();
        lblSavedBusinessRule.Visible = true;

        //BusinessRuleMailedContactCollection cBusinesRuleMailedContact = new BusinessRuleMailedContactCollection();
        //IPredicateExpression filterContact = new PredicateExpression();
        //filterContact.Add(BusinessRuleMailedContactFields.BusinesRuleId == eBusinessRule.BusinessRuleId);
        //cBusinesRuleMailedContact.DeleteMulti(filterContact);


    }


    protected void Cancel(object sender, EventArgs e)
    {
        Response.Redirect("BusinessRuleList.aspx");
    }

    #endregion methods


    protected void cmbType_SelectedIndexChanged(object sender, EventArgs e)
    {
        ShowExtraFields();
    }

    private void ShowExtraFields()
    {
        try
        {
            switch (Convert.ToInt32(cmbType.SelectedValue))
            {
                case Parameters.CALL_TYPE:
                    trLetter1.Visible = true;
                    trLetter2.Visible = true;
                    trMail.Visible = false;
                    trCall.Visible = true;
                    trTemplate.Visible = false;
                    trMail1.Visible = false;
                    break;
                case Parameters.LETTER_TYPE:
                    trLetter1.Visible = true;
                    trLetter2.Visible = true;
                    trMail.Visible = false;
                    trCall.Visible = false;
                    trTemplate.Visible = true;
                    trMail1.Visible = false;
                    break;
                case Parameters.MAIL_TYPE:
                    trLetter1.Visible = false;
                    trLetter2.Visible = false;
                    trMail.Visible = true;
                    trMail1.Visible = true;
                    trCall.Visible = false;
                    trTemplate.Visible = true;
                    break;
            }
        }
        catch { }
    }

}
